﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using CoreLib.Message;
using Tracy.CoreLib;

namespace Tracy
{
    public class AbstractMessageHandlerForm: Form
    {
        protected delegate void UpdateUICallbackMessage(object sender, TracyMessageEventArgs e);
        protected delegate void UpdateUICallbackGeneral(object sender, TracyGeneralEventArgs e);
        /// <summary>
        /// 消息处理已经完成，刷新UI
        /// </summary>
        protected void tracyEngine_OnMessageProcessed(object sender, TracyMessageEventArgs e)
        {
            if (this.IsDisposed) return;
            if (this.InvokeRequired)
            {
                UpdateUICallbackMessage d = new UpdateUICallbackMessage(tracyEngine_OnMessageProcessed);
                this.Invoke(d, new object[] { sender, e });
            }
            else
            {
                if (e.Message.Sender == this)
                {
                    HandleMessageReceived(e.Message);
                }
                if (HandleGeneralException(e.Message))
                {
                    EndProcessMessage(e.Message);
                }
            }
        }

        /// <summary>
        /// 收到返回消息
        /// </summary>
        protected virtual void HandleMessageReceived(ITracyMessage msg)
        {
            
        }

        /// <summary>
        /// 检查并处理异常
        /// </summary>
        /// <param name="e"></param>
        /// <returns>true:未发现异常; false:发现异常</returns>
        protected virtual bool HandleGeneralException(ITracyMessage msg)
        {
            if (msg.Sender == this && msg.MessageException != null)
            {
                HandleException(msg.MessageException);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 处理异常
        /// </summary>
        protected virtual void HandleException(Exception e)
        {
            //TODO:更高级的错误处理
            MessageBox.Show(e.Message);
        }

        protected virtual void EndProcessMessage(ITracyMessage msg)
        {
            
        }
    }
}
